﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using dslUf.U8Sync.U8SyncAll.Post;
using zUfDsl.Models;
using zUfDsl.ModelUF;
using zUfDsl.Sync;
using zUfDsl.Sync.Post;

namespace zUfDsl.Sync
{

    public partial class SyncData : UserControl
    {
        #region 系统初始化
        private delegate void SetVal();
        private delegate string GetVal(Control c);
        private zUfDsl.Models.tipConfig _tipconfig;
        private Common.HandleDataGrid _handleDataGrid;
        private delegate List<T> GetValList<T>(DataGridView c);



        public SyncData()
        {
            try
            {
                InitializeComponent();
                _handleDataGrid = new Common.HandleDataGrid();
                this.labTip.Text = $"账套：{cHandleUF.cAccID}；用户名{cHandleUF.cUserName}；" +
    $"登陆日期{cHandleUF.dLoginDate.ToString("yyyy-MM-dd")}。" +
    $"程序版本【{cHandleUF.cVerion.ToString("yyyy-MM-dd")}】";
                this.tbServer.Text = Common.HandleRegistry.ReadKey("ufSyncUrl", "DslUf", "http://192.168.18.135:8088/api/u8/U8Sync/SyncAll");
                using (var db = new Common.HandleDb().GetUfsystem())
                {
                    var tmpsource = db.UA_Account.FirstOrDefault(s => s.cAcc_Id == cHandleUF.cAccID);
                    tbSource.Text = $"[{tmpsource.cAcc_Id}]{tmpsource.cAcc_Name}";
                    tbSource.ReadOnly = true;                    
                    InitGrid(db);
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message + ex.StackTrace); }
        }
        #endregion
        #region 初始化Grid
        private void InitGrid(U8DataContext db)
        {
            #region 初始化格式
            var lcolset = new List<reportColumns>();

            var tmpcolindex = new reportColumns() { Code = "rowindex", Title = "行号", Align = 2, Width = 60, bModify = false, iOrder = 1 };
            lcolset.Add(tmpcolindex);
            //tmpcolindex = new reportColumns() { Code = "rowindex", Title = "行号", Align = 2, Width = 60, bModify = false, iOrder = 1 };
            //lcolset.Add(tmpcolindex);
            var tmpcball = new reportColumns() { Code = "cball", Title = "cball", Align = 2, Width = 50, bModify = true, iOrder = 3 };
            lcolset.Add(tmpcball);
            var tmpcol = new reportColumns() { Code = "cAcc_Id", Title = "账套号", Align = 1, Width = 100, bModify = false, iOrder = 4 };
            lcolset.Add(tmpcol);
            tmpcol = new reportColumns() { Code = "cAcc_Name", Title = "账套名称", Align = 1, Width = 200, bModify = false, iOrder = 5 };
            lcolset.Add(tmpcol);
            _handleDataGrid.InitGrid(this.superGridSum1, lcolset);
            this.superGridSum1.Sorted += _handleDataGrid.dtvSorted;
            #endregion
            #region 初始化数据
            //var sql = $"select cAcc_Id,cAcc_Name from UA_Account where cAcc_ID<>{cHandleUF.cAccID} order by cAcc_ID";
            //var dt = db.GetDataTable(sql);
            var l_acc = db.UA_Account.Where(s => s.cAcc_Id != cHandleUF.cAccID)
                .Select(s => new accountSel { cAcc_Id = s.cAcc_Id, cAcc_Name = s.cAcc_Name })
                .OrderBy(s => s.cAcc_Id)
                .ToList();
            _handleDataGrid.BlindData(l_acc);

            var l_accsel = db.zAccountSel.Where(s => s.cAccIDSource == cHandleUF.cAccID).ToList();
            if (l_accsel.Count > 0)
            {
                var t0 = l_accsel[0];
                this.cbBom.Checked = t0.bBom==true?true:false;
                this.cbInv.Checked=t0.bInv==true?true:false;
                this.tbInventoryClass.Text = t0.InventoryClass.ObjToString().Length == 0 ? "全部" : t0.InventoryClass;
                for (int i = 0; i < this.superGridSum1.Rows.Count; i++)
                {
                    var trow = this.superGridSum1.Rows[i];
                    var accid = trow.Cells["cAcc_Id"].Value.ToString();
                    var tmpjud = l_accsel.FirstOrDefault(s => s.cAccID == accid);
                    if (tmpjud != null)
                    {
                        trow.Cells["cball"].Value = true;
                    }
                }
                _handleDataGrid.AddRowIndex(this.superGridSum1);
            }
            #endregion
        }
        #endregion

        private void labTipClick(object sender, EventArgs e)
        {
            MessageBox.Show(cHandleUF.cConnstr);
        }

        private void btSync_Click(object sender, EventArgs e)
        {
            try
            {
                Common.HandleButton.SyncButton(this.btSync, "同步", ref this._tipconfig, btSync_ClickProc);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btSync_ClickProc()
        {
            try
            {
                var delget = new GetVal(_handleDataGrid.GetControlValue);
                var cbinv = this.Invoke(delget, this.cbInv).ObjToBool();
                var cbbom = this.Invoke(delget, this.cbBom).ObjToBool();
                var cinvccode = this.Invoke(delget, this.tbInventoryClass).ObjToString();
                var delgetall = new GetValList<accountSel>(GetDataGridSel);
                var l_source = (List<accountSel>)this.Invoke(delgetall, this.superGridSum1);
                var l_selnew = l_source.Select(s => new zAccountSel() { cAccIDSource = cHandleUF.cAccID, cAccID = s.cAcc_Id, dMDate = DateTime.Now }).ToList();
                #region 保存选择的账套
                using (var db = new Common.HandleDb().GetUfsystem())
                {
                    var l_accsel = db.zAccountSel.Where(s => s.cAccIDSource == cHandleUF.cAccID).ToList();
                    var l_del = new List<zAccountSel>();
                    for (int i = 0; i < l_accsel.Count; i++)
                    {
                        var t = l_accsel[i];
                        var tmpjud = l_selnew.FirstOrDefault(s => s.cAccID == t.cAccID);
                        if (tmpjud == null)
                        {
                            l_del.Add(t);
                        }
                        else
                        {
                            if (t.bBom != cbbom) { t.bBom = cbbom; }
                            if (t.bInv != cbinv) { t.bInv = cbinv; }
                            if (t.InventoryClass != cinvccode) { t.InventoryClass = cinvccode; }
                        }
                    }
                    var l_add = new List<zAccountSel>();
                    for (int i = 0; i < l_selnew.Count; i++)
                    {
                        var t = l_selnew[i];
                        var tmpjud = l_accsel.FirstOrDefault(s => s.cAccID == t.cAccID);
                        if (tmpjud == null)
                        {
                            t.bBom = cbbom;
                            t.bInv = cbinv;
                            t.InventoryClass = cinvccode;
                            l_add.Add(t);
                        }
                    }
                    if (l_del.Count > 0) { db.zAccountSel.DeleteAllOnSubmit(l_del); }
                    if (l_add.Count > 0) { db.zAccountSel.InsertAllOnSubmit(l_add); }
                    db.SubmitChanges();
                }
                #endregion


                var post = new SyncPost()
                {
                    AccIDSource = cHandleUF.cAccID,
                    bSyncBom = cbbom,
                    bSyncInv = cbinv,
                    cSyncPerson = cHandleUF.cUserName,
                    AccountsDesc = l_selnew.Select(s => s.cAccID).ToArray(),
                    cInvCCodes=cinvccode,
                };
                var url = this.Invoke(delget, this.tbServer).ObjToString();
                Common.HandleRegistry.SaveKey("ufSyncUrl", "DslUf", url);
                var icount = 0;
                while (icount < 10000)
                {
                    var ss = new Common.HandleHttp(url, false).Post(post);
                    var rval = Common.HandleJSON.Deserialize<U8RetVal<UserTipModel>>(ss);
                    if (rval.errcode == -1)
                    {
                        _tipconfig.cMsg = rval.errmsg;
                        _tipconfig.bSuc = false;
                        return;
                    }
                    else if (rval.errcode == 1)
                    {
                        var t = rval.data;
                        if (t.iComplete == iCompleteEnum.已完成)
                        {
                            _tipconfig.cMsg = t.cTip;
                            _tipconfig.bSuc = !t.bErr;
                            return;
                        }
                        else
                        {
                            if (t.ival != 0 && t.iMax != 0)
                            {
                                _tipconfig.tip = $"{t.cTip}[{t.ival}/{t.iMax}]";
                            }
                            else
                            {
                                _tipconfig.tip = t.cTip;
                            }
                            _tipconfig.itotal = 100;
                            _tipconfig.ival = t.iPercent;
                        }
                    }
                    icount++;
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private List<accountSel> GetDataGridSel(DataGridView dgv)
        {
            var list_sour = new List<accountSel>();
            if (dgv.Rows.Count == 0) { return list_sour; }
            var currentcell = dgv.CurrentCell;
            int icol = 0;
            for (int j = 0; j < dgv.Columns.Count; j++)
            {
                if (dgv.Columns[j].Visible)
                {
                    icol = j;
                    break;
                }
            }
            var tmp1 = dgv.Rows[0].Cells[icol];
            dgv.CurrentCell = tmp1;
            dgv.CurrentCell = currentcell;
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                var dgr = dgv.Rows[i];
                if (dgr.Cells["cball"].Value.ObjToBool() == true)
                {
                    var tmp_row = _handleDataGrid.GridRowToObj<accountSel>(dgr);
                    list_sour.Add(tmp_row);
                }
            }
            return list_sour;
        }

        private void SyncData_Load(object sender, EventArgs e)
        {

        }
        #region 显示日志
        private void button1_Click(object sender, EventArgs e)
        {
            var flog = new FrmLog();
            flog.Show();
        }
        #endregion

        #region 选择存货分类
        private void btSelInvCCode_Click(object sender, EventArgs e)
        {
            try
            {
                using (var f = new FrmInventoryClass(this.tbInventoryClass.Text))
                {
                    f.ShowDialog();
                    this.tbInventoryClass.Text = f.GetSel();
                    f.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}_{ex.StackTrace}");
            }
        }
        #endregion

        private void cbInv_CheckedChanged(object sender, EventArgs e)
        {
            if (cbInv.Checked)
            {
                this.btSelInvCCode.Enabled = true;
            }
            else
            {
                this.btSelInvCCode.Enabled = false;
            }
        }
    }
}
